package com.freight.file.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.redis.RedisTemplateHelper;
import com.freight.core.common.utils.HttpUtils;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.file.constants.FileConstant;
import com.freight.file.vo.CompanyPicFileVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

import static com.freight.file.util.BaiDuToken.getAuth;

public class CompanyOcrUtil {



    //百度地址
    public static String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license";


    public static CompanyPicFileVo baiDuJustCompany(String imgBase64, RedisTemplateHelper redisTemplate) {

        HashMap<String, Object> result = new HashMap<>();
        Map<String, Object> resMap = new HashMap<String, Object>();
        CompanyPicFileVo resO = null;
        try {
            String param = "image=" + imgBase64;

            if(redisTemplate.get("baiduAccessToken")==null){
                getAuth(redisTemplate);
            }
            String accessToken = redisTemplate.get("baiduAccessToken");
            String res = HttpUtil.post(url, accessToken, param);
            System.out.println(res);

            JSONObject res_obj = JSON.parseObject(res);
            if(res_obj.containsKey("error_code")){
                throw new FreightException("图片不清楚，请重新上传");
            }
            JSONObject companyjson = res_obj.getJSONObject("words_result");

            resMap.put("certNo", companyjson.getJSONObject("社会信用代码").getString("words"));
            resMap.put("companyName", companyjson.getJSONObject("单位名称").getString("words"));
            resMap.put("type", companyjson.getJSONObject("类型").getString("words"));
            resMap.put("companyUserName", companyjson.getJSONObject("法人").getString("words"));
            resMap.put("startDate", companyjson.getJSONObject("成立日期").getString("words"));
            resMap.put("endDate", companyjson.getJSONObject("有效期").getString("words"));
            resMap.put("street", companyjson.getJSONObject("地址").getString("words"));
            resMap.put("capital", companyjson.getJSONObject("注册资本").getString("words"));
            resMap.put("business", companyjson.getJSONObject("经营范围").getString("words"));
            resO = (CompanyPicFileVo) ObjectUtil.autoFillMapFields(resMap, CompanyPicFileVo.class);

            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resO;
    }

}
